<style>
  .form-item{
    margin-left: 10px;
    text-align: center;
    vertical-align: middle;
    margin-bottom: 5px;
    margin-top: 5px;
  }
  .topbutton{
    margin-top: 5px;
  }
</style>

<template>

  <div>
    <!-- <el-row>
      <el-button plain>新增</el-button>
    </el-row> -->
    <el-form :inline="true">
      <el-form-item label="选择站区" class="form-item">
        <el-select v-model="searchMap.zhanquid" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.zqid"
            :label="item.zaname"
            :value="item.zqid"
          />
        </el-select>
      </el-form-item>

      <el-button type="primary" class="topbutton" @click="selectPage()">查询</el-button>
      <el-button type="primary" @click="handleEdit('')">新增</el-button>
      <el-button type="primary" @click="handleXls()">导入</el-button>
      <el-button type="primary" @click="open()">导出</el-button>
    </el-form>
    <el-table
      :data="list"
      border
      style="width: 100%"
    >
      <el-table-column
        fixed
        prop="gqname"
        label="工区"
        width="200"
        align="center"
      />
      <el-table-column
        fixed
        prop="zqname"
        label="所属站区"
        width="200"
        align="center"
      />
      <el-table-column
        prop="ganhaoname"
        label="杆号"
        min-width="120"
        align="center"
      />

      <el-table-column
        prop="workshop"
        label="车间"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="linetype"
        label="线别"
        min-width="200"
        align="center"
      />

      <el-table-column
        prop="zztype"
        label="杆型"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="gonglibiao"
        label="对应公里标"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="sdname"
        label="所在隧道"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="rfid"
        label="RFID编号"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="overview"
        label="设备名称（简述）"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="remark"
        label="备注"
        min-width="300"
        align="center"
      />


      <el-table-column
        prop="positioning"
        label="定位"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="sdn"
        label="支持装置性质"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="sdf"
        label="支持装置形式"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="changeDate"
        label="更换日期"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="pillarModelNumber"
        label="支柱型号编号"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="sdn2"
        label="支持装置2"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="positioningMethod"
        label="定位方式"
        min-width="300"
        align="center"
      />




      <el-table-column
        label="操作"
        min-width="180"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleClick(scope.row.ganhaoid)">施工记录</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row.ganhaoid)">修改</el-button>
          <!-- <el-button type="text" size="small" @click="handleDelete(scope.row.ganhaoid)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :total="total"
      :current-page.sync="curentPage"
      :page-sizes="[10,20,50]"
      :page-size="10"
      @size-change="sizeData"
      @current-change="pageData"
    />
    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属站区">
              <el-select v-model="pojo.zhanquId" clearable placeholder="请选择" style="width:100%" @change="selectChanged">
                <el-option
                  v-for="item in options"
                  :key="item.zqid"
                  :label="item.zaname"
                  :value="item.zqid"
                />
              </el-select></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="杆号名称"><el-input v-model="pojo.ganhaoname" /></el-form-item>
          </el-col>
        </el-row>
<!-- -----新增车间与线别 -->
<el-row>
<el-col :span="12">
            <el-form-item label="所在车间">
              <el-select v-model="pojo.cjId" clearable placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in chejianoptions"
                  :key="item.chejianid"
                  :label="item.workshop"
                  :value="item.chejianid"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所在线别">
              <el-select v-model="pojo.xbId" clearable placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in xianbieoptions"
                  :key="item.xianbieid"
                  :label="item.linetype"
                  :value="item.xianbieid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          </el-row>
<!-- --- -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="杆型"><el-input v-model="pojo.zztype" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公里标"><el-input v-model="pojo.gonglibiao" /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="RFID号"><el-input v-model="pojo.rfid" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在隧道">
              <el-select v-model="pojo.sdId" clearable placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in suidaooptions"
                  :key="item.tunnelid"
                  :label="item.tnname"
                  :value="item.tunnelid"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备简述"><el-input v-model="pojo.overview" type="textarea" /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注"><el-input v-model="pojo.remark" type="textarea" /></el-form-item>
          </el-col>
        </el-row>

        <el-row align="right" style="text-align:right">
          <el-button type="primary" @click="handleSave()">保存</el-button>
          <el-button @click="dialogFormVisible = false">关闭</el-button>
        </el-row>

      </el-form>

    </el-dialog>


          
      <el-dialog title="导入excel" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
			ref="upload"
			:accept="fileType.join(',')"
			:limit="1"  
      :before-upload="beforeUpload"
			:action="upload.url"
			:disabled="upload.isUploading"
			:on-progress="handleFileProgress"
			:on-success="handleFileSuccess"
			:auto-upload="false"
      :on-error="handleFileError"
			drag
			>
      <!-- :on-error="handleFileError"  :before-upload="beforeUpload" -->

			<i class="el-icon-upload" />
			<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			<div slot="tip" class="el-upload__tip" style="color: red">
				提示：仅允许导入“xls”或“xlsx”格式文件！
			</div>
			</el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog> 



  </div>
</template>

<script>
import ganhao from '@/api/baseData/ganhao'
// import zhanqu from '@/api/base/zhanqu'
// import tunnel from '@/api/base/tunnel'
// // -----
// import chejian from '@/api/base/chejian'
// import xianbie from '@/api/base/xianbie'
// -----
export default {

  data() {
    return {
      list: [],
      total: 0,
      searchMap: {
        curPage: 1,
        pageSize: 10,
        zhanquid: ''
      },
      dialogFormVisible: false,
      id: '', // 主键，新增修改的主键
      pojo: {},
      options: [], // 顶部查询时候用
      curentPage: 1,
      suidaooptions: [],
      // -----车间线别查询容器
      chejianoptions: [],
      xianbieoptions: [],
      // -----
      equiptypeoptions: [], // 新增修改时候用
      // value: ''

      fileType: ['.xlsx', '.xls'],
				upload: {
					// // 是否显示弹出层（用户导入）
					open: false,
					// // 弹出层标题（用户导入）
					title: "",
					// // 是否禁用上传
					isUploading: false,
					// // 设置上传的请求头部
					// headers: { Authorization: getToken() },
					// 上传地址
					url:'//localhost:8081/phm/ganhao/excel/excelImport',
					// // 是否更新已经存在的用户数据
					isUploading: false
				}
    }
  },
  created() {
    this.fetchData()
    this.fetchzhanquAllList()
  },
  methods: {
    handleXls(){
      this.upload.open=true;
    },
    //导出数据
    open() {
      this.$confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认后执行的操作
        this.sendRequest();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });          
      });
    },
    sendRequest() {
      // 这里放置的请求逻辑
      ganhao.excelExport()
      .then(res => {
                console.log(res); // 控制台输出：Blob {size: 30208, type: 'application/x-msdownload'}
                var debug = res;
                if (debug) {
                    var elink = document.createElement('a');
                    elink.download = '杆号支柱管理.xlsx';
                    elink.style.display = 'none';
                    var blob = new Blob([debug], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                    elink.href = URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                    this.$message({
                        type: 'success',
                        message: '导出成功!'
                })
                } else {
                    this.$message.error('导出异常请联系管理员');
                }
            }).catch(error => {
          console.log(error)
          this.$message({
            type: 'error',
            message: '导出失败!'
          });
        });
    },

    // 导入数据

	 // 文件上传中处理
			handleFileProgress() {
				this.upload.isUploading = true
			},
			// 文件上传成功处理
			handleFileSuccess() {
        this.$message({
          type: 'success',
           message: '导入成功!'
                })
				this.upload.isUploading = false
				this.$refs.upload.clearFiles()
				this.upload.open=false  // 关闭弹窗
				//刷新当前列表
			},
			// 提交上传文件
			submitUpload() {
				this.$refs.upload.submit()
			},
			// 上传文件之前的钩子
			beforeUpload(file) {
				const isXlS =
					file.type ===
					"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
					file.type === "application/vnd.ms-excel";
				if (!isXlS) {
					this.$message.error("仅支持xls、xlsx格式的文件!");
				}
				this.filename = file.name;
				return isXlS;
			},
			handleFileError(){
				this.$message.error("文件数据有误!");
			},

      // -------------------
    handleClick(ghid) {
      console.log(ghid)
      this.$router.push({ name: 'zhizhu', query: { ghid: ghid }})
    },
    // 顶部的查询
    selectPage() {
      this.searchMap.curPage = 1
      this.curentPage = 1
      this.fetchData()
    },

    selectChanged(value) {
      console.log(value)
      tunnel.listByZqid({ zqid: value }).then(res => {
        console.log(res)  
        this.suidaooptions = res.data
      })

      // -----
      chejian.listByZqid({ zqid: value }).then(res => {
        console.log(res)  
        this.chejianoptions = res.data
      })

      xianbie.listByZqid({ zqid: value }).then(res => {
        console.log(res)  
        this.xianbieoptions = res.data
      })
    },
    /*
    根据ganhaoid查询杆号的名字
    */
    findZhanquName(zqid) {
      for (var i = 0; i < this.options.length; i++) {
        if (this.options[i].zqid === zqid) {
          return this.options[i].zaname
        }
      }
      return ''
    },
    fetchData() {
      console.log(this.searchMap)
      // this.searchMap.curPage = 1
      ganhao.fetchList(this.searchMap).then(res => {
        console.log(res)
        this.list = res.data.records
        this.total = res.data.total
      })
    },
    dataFormat(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      // return moment(date).format('YYYY-MM-DD')引用moment格式化日期
    },
    sizeData(limit) {
      console.log(limit)
      this.searchMap.pageSize = limit
      this.fetchData()
    },
    pageData(page) {
      this.searchMap.curPage = page
      this.fetchData()
    },
    // 新增和修改用同一个函数，新增不传 ID ,修改传ID过来
    handleEdit(id) {
      console.log(id)
      this.dialogFormVisible = true
      if (id !== '') {
        ganhao.findById(id).then(res => {
          console.log(res)
          this.pojo = res.data
          this.id = id
          // this.imageUrl=this.pojo.imageUrl
        })
      } else {
        this.id = ''
        this.pojo = {}
        this.imageUrl = ''
      }
    },
    handleDelete(id) {
      this.$confirm('此操作删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        ids.push(id)

        ganhao.deleteByIds(ids).then(res => {
          this.$message({
            type: (res.code === 200 ? 'success' : 'error'),
            message: res.msg
          })
          if (res.code === 200) {
            this.fetchData()
          }
        })
        // 向服务器发请求
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 保存数据的方法
    handleSave() {
      // 向后端发送 数据
      this.pojo.zaname = this.findZhanquName(this.pojo.zhanquId)
      ganhao.update(this.id, this.pojo).then(res => {
        // 修改 或者新增成功
        this.$message({
          message: res.msg,
          type: (res.code === 200 ? 'success' : 'error')
        })
        if (res.code === 200) {
          this.fetchData()
        }
        this.dialogFormVisible = false
      })
    },
    // 查询所有站区分类
    fetchzhanquAllList() {
      zhanqu.fetchallList().then(res => {
        console.log(res)
        this.options = res.data
        // this.equiptypeoptions = res.data
      })
    }

  }
}
</script>
